#!/usr/bin/env zsh

# Bail out when zsh/system is not available
zmodload zsh/system || {
    __zgenom_err 'Could not load `zsh/system` which is needed for autoupdate. Please create an issue.'
    return 1
}

function __zgenom_should_autoupdate() {
    local days=$1
    local file="$ZGEN_DIR/.zgenom-$2-lastupdate"
    local last_update
    if [[ ! -f $file ]]; then
        # We've never run, create the lastupdate-file and set now as interval.
        printf 0 > $file
        last_update=$now
    else
        last_update=$(( $now - $(< $file) - $days * 86400 ))
    fi

    if [[ $last_update -ge 0 ]]; then
        if [[ -n $verbose ]]; then
            if [[ $last_update -eq $now ]]; then
                __zgenom_out "Never automatically updated '$2'."
            else
                __zgenom_out "It has been $(( $last_update / 86400 + $days)) days since your last $2 update."
            fi
        fi
        return 0
    fi
    return 1
}

function __zgenom_autoupdate() {
    emulate -L zsh
    # Using ls and awk instead of stat because stat has incompatible arguments
    # on linux, macOS and FreeBSD.
    local zgenom_owner=$(command ls -ld $ZGEN_DIR | awk '{print $3}')
    local updated=0

    # Don't update if we're running as different user than whoever
    # owns ZGEN_DIR. This prevents sudo runs from leaving root-owned
    # files & directories in ZGEN_DIR that will break future update
    # runs by the user.
    if [[ "$zgenom_owner" == "$USER" ]]; then
        local lockfile="$HOME/.zgenom-autoupdate-lock"
        printf '' > "$lockfile"
        # Create lock, don't retry to obtain a lock
        if zsystem flock -t 0 "$lockfile" &>/dev/null; then
            local now=$(command date '+%s')

            # Update self
            if [[ -n $self ]] && __zgenom_should_autoupdate $self system; then
                [[ -n $verbose ]] && __zgenom_err "Updating zgenom ..."
                zgenom selfupdate --no-reset && __zgenom_out && updated=1
            fi

            # Update plugins
            if [[ -n $plugin ]] && __zgenom_should_autoupdate $plugin plugin; then
                [[ -n $verbose ]] && __zgenom_err "Updating plugins ..."
                zgenom update --no-reset && updated=1
            fi

            # Reset only when updated
            [[ $updated -ge 1 ]] && zgenom reset && __zgenom_out

            # Release the lock
            printf '' > "$lockfile"

            # Remove lock file
            { command rm -f "$lockfile" } &!
        fi
    else
        if [[ -n "$DEBUG" ]]; then
            __zgenom_out "Skipping autoupdate of plugins because $USER doesn't own $ZGEN_DIR."
        fi
    fi

    # Return true if updated
    [[ $updated -ge 1 ]]
}

__zgenom_autoupdate $@
